package com.jingxuan.util;

import static org.assertj.core.api.Assertions.assertThat;

import java.time.LocalDateTime;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.jingxuan.util.UserBehaviorAlgorithm.BrowseRecord;

/**
 * Verifies serialization compatibility for {@link UserBehaviorAlgorithm} records.
 */
class UserBehaviorAlgorithmSerializationTest {

    private ObjectMapper mapper;

    @BeforeEach
    void setUp() {
        mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
    }

    @Test
    void browseRecord_shouldIgnoreLegacyDurationSecondsField() throws Exception {
        String json = """
            {
              "@class":"com.jingxuan.util.UserBehaviorAlgorithm$BrowseRecord",
              "userId": 42,
              "productId": "SKU-001",
              "startTime": "2024-07-24T12:00:00",
              "endTime": "2024-07-24T12:00:03",
              "durationSeconds": 5.0
            }
            """;

        BrowseRecord record = mapper.readValue(json, BrowseRecord.class);

        assertThat(record.getUserId()).isEqualTo(42L);
        assertThat(record.getProductId()).isEqualTo("SKU-001");
        assertThat(record.getStartTime()).isEqualTo(LocalDateTime.parse("2024-07-24T12:00:00"));
        assertThat(record.getEndTime()).isEqualTo(LocalDateTime.parse("2024-07-24T12:00:03"));
    }

    @Test
    void summary_shouldIgnoreLegacyEmptyFlag() throws Exception {
        String json = """
            {
              "@class":"com.jingxuan.util.UserBehaviorAlgorithm$UserBehaviorSummary",
              "userId": 1,
              "empty": true,
              "searchRecords": [],
              "browseRecords": []
            }
            """;

        UserBehaviorAlgorithm.UserBehaviorSummary summary =
            mapper.readValue(json, UserBehaviorAlgorithm.UserBehaviorSummary.class);

        assertThat(summary.getUserId()).isEqualTo(1L);
        assertThat(summary.getSearchRecords()).isEmpty();
        assertThat(summary.getBrowseRecords()).isEmpty();
    }
}
